/*
 * @Author: yangzonglong
 * @Date: 2021-02-24 10:03:00
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-11 18:00:11
 * @Auditor:
 */
import React, { useRef, memo } from 'react';
import { useDrag, DragSourceMonitor } from 'react-dnd';
import Icon from './../../../components/icon/Icon';
import { dragSourceMap } from './../../../config';
import { MenuProps, ControlProps, DragSourceProps } from './../../../interface';

interface IProps {
  item: MenuProps;
  addControl(control: MenuProps): void;
  appendControl(menu: MenuProps, control: ControlProps): void;
  setDragSource(data: DragSourceProps): void;
}

export default memo(({ item, addControl, appendControl, setDragSource }: IProps) => {
  const ref = useRef<HTMLDivElement>(null);

  const [, drag] = useDrag({
    type: 'add_' + item.type,

    item: () => { 
      setDragSource(dragSourceMap.MENU);
      return {};
     },

    collect: (monitor: DragSourceMonitor) => ({
      isDragging: monitor.isDragging(),
    }),

    end(_: unknown, monitor: DragSourceMonitor) {
      const result: any = monitor.getDropResult();

      setDragSource(dragSourceMap.NONE);

      if (result) {
        if (result.data) {
          // 向指定控件添加子控件
          return appendControl(item, result.data);
        }
        addControl(item);
      }
    },
  });

  drag(ref);

  return (
    <div ref={ref}>
      <Icon icon={item.icon} />
      <span title={item.title}>{item.title}</span>
    </div>
  );
});
